package com.itheima.ydd.commom;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.ydd.entity.YddArticle;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 *  公共数据字段的填充
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增操作自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段数据填充[INSERT]...");
        log.info(metaObject.toString());

        if (metaObject.getOriginalObject().getClass() == YddArticle.class) {
            metaObject.setValue("createDate", System.currentTimeMillis());
            metaObject.setValue("updateDate", System.currentTimeMillis());
            return;
        }

        metaObject.setValue("createDate", LocalDateTime.now());
        metaObject.setValue("updateDate", LocalDateTime.now());
    }


    /**
     * 修改操作自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段数据填充[UPDATE]...");
        log.info(metaObject.toString());

        if (metaObject.getOriginalObject().getClass() == YddArticle.class) {
            metaObject.setValue("updateDate", System.currentTimeMillis());
            return;
        }
        metaObject.setValue("updateDate", LocalDateTime.now());
    }
}
